package team.first.mongodb;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

public class MongoGenreDemo {
    public static void main(String[] args) {
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);

        MongoCredential mongoCredential = MongoCredential.createCredential("user", "movie_db", "123456".toCharArray());

        MongoClient mongoClient = new MongoClient(
                serverAddress, mongoCredential, MongoClientOptions.builder().build()
        );

        // 获取数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("movie_db");

        // 获取数据库中指定名字的集合
        MongoCollection<Document> genre = mongoDatabase.getCollection("genre");

        /* 直接使用HashMap，插入到数据库中的文档的属性是乱序的，使用LinkedHashMap是有序的
        Map<String, Object> val1 = new HashMap<>();
        Map<String, Object> val2 = new HashMap<>();
        val1.put("id", 1);
        val2.put("name", "剧情");
        val1.put("id", 2);
        val1.put("name", "动作");

        // 创建新的文档对象
        Document genreDoc1 = new Document(val1);
        Document genreDoc2 = new Document(val2);

        // 将文档插入到数据库中
        genre.insertOne(genreDoc1);
        genre.insertOne(genreDoc2);
        */

        // 直接创建文档对象并赋值
        /*Document genreDoc11 = new Document("id", "2").append("name", "爱情");
        Document genreDoc22 = new Document("id", "2").append("name", "爱情");

        List<Document> documentList = Arrays.asList(genreDoc11, genreDoc22);
        genre.insertMany(documentList);*/

        // 传统的写法
        /*try {
            List<Entity> entities = Db.use().query("SELECT * FROM type");
            List<Document> docList = new ArrayList<>();
            for(int i = 0; i < entities.size(); i++){
                Entity entity = entities.get(i);
                Document doc = new Document("id", entity.getInt("id"))
                        .append("name", entity.getStr("name"));
                docList.add(doc);
            }
            genre.insertMany(docList);
        } catch (SQLException e) {
            e.printStackTrace();
        }*/

        // 利用java 8 的新特性的写法
        try {
            List<Entity> entities = Db.use().query("SELECT * FROM genre");
            List<Document> docList = entities.stream().map(entity -> {
                Document document = new Document("id", entity.getInt("id")).append("name", entity.getStr("name"));
                return document;
            }).collect(Collectors.toList());

            genre.insertMany(docList);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
